<template>
  <el-dialog v-model="dialogVisibleInner" :title="dialogTitle" top="5vh" width="60%" draggable
    :fullscreen="isFullscreen" :close-on-press-escape="false" :close-on-click-modal="false" @close="handleClose"
    body-class="dialogBody">
    <template #header>
      <div class="dialog-header">
        <div class="dialog-header-title">
          <span>{{ dialogTitle }}</span>
        </div>
        <div class="header-buttons">
          <el-icon v-if="Action === 4" style="margin:14px 15px 0 0;cursor: pointer" class="maximize-button"
            @click="toggleFullscreen">
            <FullScreen class="icon-button" v-if="!isFullscreen" />
            <Minus class="icon-button" v-else />
          </el-icon>
        </div>
      </div>
    </template>

    <el-form :model="dialogForm" label-width="100px" :rules="rules" ref="dialog">
      <el-form-item label="标题" prop="Title">
        <el-input v-model="dialogForm.Title" :readonly="Action === 4" :style="titleStyle" maxlength="32" />
      </el-form-item>
      <el-form-item label="分类" v-show="Action !== 4 && joinType === 1" prop="ClassID">
        <el-cascader :popper-class="color === 'night' ? 'nightClass' : ''" style="width:100%"
          v-model="dialogForm.ClassID" :options="classList"
          :props="{ value: 'value', label: 'label', children: 'children', emitPath: false, expandTrigger: 'hover', checkStrictly: false }"
          placeholder="请选择分类" class="full-width" @change="handleChange">
        </el-cascader>
      </el-form-item>
      <!-- <el-form-item label="分类" v-show="Action !== 4 && joinType === 1" prop="ClassID">
        <el-cascader ref="cascaderRef" style="width:100%" v-model="dialogForm.ClassID" :options="classList"
          :props="cascaderProps" :popper-class="color === 'night' ? 'nightClass' : ''" placeholder="请选择分类"
          class="full-width" @change="handleChange">
          <template #default="{ node, data }">
            <span class="custom-label" @click.stop="onLabelClick(node)">
              {{ node.label }}
            </span>
          </template>
        </el-cascader>
      </el-form-item> -->
      <el-form-item label="分类" v-show="Action !== 4 && joinType === 2" prop="Property">
        <el-select v-model="dialogForm.ClassID" placeholder="请选择分类" class="full-width"
          :popper-class="color === 'night' ? 'nightClass' : ''">
          <el-option v-for="item in classList" :key="item.Id" :label="item.Name" :value="item.Id" />
        </el-select>
      </el-form-item>
      <el-form-item label="属性" v-show="Action !== 4 && joinType === 1" prop="Property">
        <el-select v-model="dialogForm.Property" placeholder="请选择属性" class="full-width"
          :popper-class="color === 'night' ? 'nightClass' : ''">
          <el-option label="私有" :value="1" />
          <el-option label="共享" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="ContentLink">
        <div class="dialog-content" :style="Action === 4 ? 'display:flex;flex:1;' : 'width:100%;'">
          <div v-show="Action !== 4 && dialogVisibleInner">
            <wang-editor v-if="editorReady" v-model="dialogForm.ContentLink"></wang-editor>
          </div>
          <div :style="contentStyle" class="chat-message-text" v-html="formattedContent" v-show="Action === 4"></div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" v-show="Action !== 4">确认</el-button>
        <el-button type="info" @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  onMounted,
  computed,
  nextTick,
} from "vue";
import "../../assets/_highlight.js@11.8.0@highlight.js/styles/monokai-sublime.css";
import hljs from "highlight.js";
import MarkdownIt from "markdown-it";
import { getuuid } from "../../utils/index";
import { ElMessage } from "element-plus";
import WangEditor from "./WangEditor/index.vue";
import { FullScreen } from "@element-plus/icons-vue";

export default defineComponent({
  name: "KnowledgeBaseDialog",
  components: {
    WangEditor,
  },
  props: {
    dialogVisible: Boolean,
    classList: Array,
    Action: Number, // 修正类型为 Number，与实际使用一致
    joinType: Number,
    dialogForm: Object,
  },
  emits: ["closeDialog", "submitDialog"],
  setup(props, { emit }) {
    onMounted(() => {
      hljs.highlightAll();
    });
    const color = ref(localStorage.getItem('isNightMode') || 'night');
    const isFullscreen = ref(false);
    const dialog = ref(null)
    // 动态计算输入框样式
    const titleStyle = computed(() => ({
      height: isFullscreen.value ? '10vh' : 'auto', // 最大化时 10vh，否者自动
    }));
    const contentStyle = computed(() => ({
      height: isFullscreen.value ? 'calc(80vh - 100px)' : '300px', // 最大化时 10vh，否者自动
    }));
    const toggleFullscreen = () => {
      isFullscreen.value = !isFullscreen.value

    }
    // 定义全局的 copy 方法
    window.knowledgecopy = function (elementId) {
      const element = document.getElementById(elementId);
      if (!element) {
        console.warn(`Element with id '${elementId}' not found.`);
        return;
      }
      const tempInput = document.createElement("textarea");
      tempInput.value = element.textContent || element.innerText;
      document.body.appendChild(tempInput);
      tempInput.select();
      try {
        document.execCommand("copy");
        ElMessage({ message: "复制成功", type: "success", duration: 5 * 1000 });
      } catch (err) {
        ElMessage({ message: "复制失败", type: "warning", duration: 5 * 1000 });
      } finally {
        document.body.removeChild(tempInput);
      }
    };

    // 初始化 Markdown 渲染器并添加图片高度规则
    const md = new MarkdownIt({
      html: true,
      typographer: true,
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            const idname = `name${getuuid()}`;
            const codeContent = hljs.highlight(str, {
              language: lang,
              ignoreIllegals: true,
            }).value;
            return `<pre class="hljs">
                      <div class="code-block-header">
                        <span class="code-block-header__lang">${lang}</span>
                        <el-button class="code-block-header__copy" onclick="window.knowledgecopy('${idname}')">复制代码</el-button>
                      </div>
                      <code id="${idname}">${codeContent}</code>
                    </pre>`;
          } catch (__) { }
        }
        return "";
      },
    }).use(function (md) {
      // 修改图片渲染规则
      const defaultRender = md.renderer.rules.image;
      md.renderer.rules.image = function (tokens, idx, options, env, self) {
        const token = tokens[idx];
        token.attrs = token.attrs || [];
        const styleIndex = token.attrs.findIndex((attr) => attr[0] === "style");
        if (styleIndex !== -1) {
          token.attrs[styleIndex][1] += ";height:500px";
        } else {
          token.attrs.push(["style", "height:500px"]);
        }
        return defaultRender(tokens, idx, options, env, self);
      };
    });

    // 计算属性处理 Markdown 内容
    const formattedContent = computed(() =>
      md.render(props.dialogForm.ContentLink || "")
    );

    const editorReady = ref(false);
    const dialogVisibleInner = ref(false);

    // 监听 dialogVisible 变化以初始化编辑器
    watch(
      () => props.dialogVisible,
      (newValue) => {
        dialogVisibleInner.value = newValue;
        if (newValue) {
          nextTick(() => {
            editorReady.value = true; // 标记编辑器可以初始化
          });
        } else {
          dialog.value.clearValidate(); // 仅清除验证状态，不重置字段值
          isFullscreen.value = false
        }
      }
    );

    // 使用计算属性动态设置标题
    const dialogTitle = computed(() => {
      switch (props.Action) {
        case 1:
          return props.joinType === 1 ? "添加智库" : "添加收藏";
        case 2:
          return props.joinType === 1 ? "修改智库" : "修改收藏";
        default:
          return props.joinType === 1 ? "预览智库" : "预览收藏";
      }
    });

    const handleClose = () => {
      dialogVisibleInner.value = false;
      emit("closeDialog");
    };
    const handleSubmit = async () => {
      try {
        // 调用表单校验（假设是 Element Plus 的 Form 组件）
        await dialog.value.validate();
        // 校验通过后触发事件
        emit('submitDialog', props.dialogForm, props.Action);
      } catch (error) {
        // 校验失败时处理
        console.error('表单校验失败:', error);
        return false;
      }
    };
    // 级联选择器打印选择的值
    const handleChange = (value) => {
      // 确保 event 是有效的，并且包含 target.value
      console.log('选择到的值:', value);
    };
    const cascaderRef = ref(null)

    // Cascader 配置
    const cascaderProps = {
      value: 'value',
      label: 'label',
      children: 'children',
      emitPath: false,
      expandTrigger: 'hover',
      checkStrictly: false
    }

    // 点击节点 label 时触发
    const onLabelClick = (node) => {
      // 如果节点可选，设置值
      emit('update:dialogForm', {
        ...props.dialogForm,
        ClassID: node.value
      })
      // 关闭下拉
      if (cascaderRef.value) {
        cascaderRef.value.blur()
      }

      console.log('选中节点:', node.label, node.value)
    }


    return {
      dialogVisibleInner,
      editorReady,
      handleClose,
      handleSubmit,
      formattedContent,
      dialogTitle,
      handleChange,
      color,
      toggleFullscreen,
      onLabelClick,
      isFullscreen,
      titleStyle,
      contentStyle,
      cascaderProps,
      rules: {
        Title: [{ required: true, message: "请输入标题" }],
        ClassID: [{ required: true, message: "请选择分类" }],
        Property: [{ required: true, message: "请选择属性" }],
        ContentLink: [{ required: true, message: "请输入内容" }]
      },
      dialog
    };
  },
});
</script>

<!-- 保持原有的 <template> 和 <script> 部分不变 -->
<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  align-items: flex-start !important;
}

.icon-button {
  color: #909399;
}

.icon-button:hover {
  color: #409eff;
}

:deep(::-webkit-scrollbar) {
  /*滚动条整体样式*/
  width: 8px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 8px;
}

:deep(::-webkit-scrollbar-thumb) {
  /*滚动条里面小方块*/
  border-radius: 5px;
  background: #cfcbcb;
}

:deep(::-webkit-scrollbar-track) {
  /*滚动条里面轨道*/
  background: #2d2c3c;
}

.full-width {
  width: 100%;
}

.chat-message-text {
  width: 100%;
  height: 300px;
  overflow-y: auto;
  align-self: flex-start;
  border-radius: 5px;
  padding: 0 10px;
  background-color: #f4f6f8;
  word-wrap: break-word;
}

.hljs {
  padding: 10px;
  border-radius: 0 0 4px 4px;
}

.code-block-header__copy {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
}

.dialog-header {
  display: flex;
  justify-content: space-between;

}

.dialog-header-title {
  display: inline-block;
  width: 180px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background: #409eff;
  color: #fff;
}

.night {
  .w-e-text-container {
    background: #2a2d3c;
  }

  .chat-message-text {
    background-color: #2a2d3c !important;
    box-shadow: 0 0 0 1px #414556 !important;
  }
}
</style>

<style>
.dialogBody {
  overflow-y: auto !important;
}

:deep(.el-dialog__header) {
  padding: 0 !important;
  /* 保持紧贴左上角 */
  margin: 0 !important;
  /* 确保无外边距 */
}
</style>